package com.niknik.woody.rest.rule;

import com.niknik.woody.rest.response.CreateRoomResponse;
import com.niknik.woody.rest.response.RoomTokenResponse;
import com.niknik.woody.rest.response.RoomsResponse;
import com.niknik.woody.rest.response.WResponse;
import com.niknik.woody.rest.schema.ResPath;
import com.sun.jersey.core.util.MultivaluedMapImpl;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import static com.niknik.woody.rest.schema.ResParam.MOVE;
import static com.niknik.woody.rest.schema.ResParam.*;
import static com.niknik.woody.rest.schema.ResPath.*;

/**
 * User: yoda
 * Date: 10.12.11
 * Time: 10:58
 */
public class MainRoomRestClient
    extends RestClient {

  public <T> T createChannel(Object playerId, Object roomId) {
    MultivaluedMap<String, String> params = new MultivaluedMapImpl();
    params = buildParams(params, PLAYER_ID, playerId);
    params = buildParams(params, ROOM_ID, roomId);
    return (T) get(CREATE_CHANNEL, params, RoomTokenResponse.class);
  }

  public <T> T create(Object playerId) {
    return (T) get(CREATE, buildParams(new MultivaluedMapImpl(), PLAYER_ID, playerId), CreateRoomResponse.class);
  }

  public <T> T getRooms(Object playerId) {
    return (T) get(ROOMS, buildParams(new MultivaluedMapImpl(), PLAYER_ID, playerId), RoomsResponse.class);
  }

  public <T> T move(Object playerId, Object roomId, Object move) {
    MultivaluedMap<String, String> params = new MultivaluedMapImpl();
    params = buildParams(params, PLAYER_ID, playerId);
    params = buildParams(params, ROOM_ID, roomId);
    params = buildParams(params, MOVE, move);
    return (T) get(ResPath.MOVE, params, WResponse.class);
  }

  protected MultivaluedMap<String, String> buildParams(MultivaluedMap<String, String> params, String paramName,
                                                       Object param) {
    if (param != null) {
      params.putSingle(paramName, param.toString());
    }
    return params;
  }

  private <T extends WResponse> T get(String pathPart, MultivaluedMap<String, String> params, Class<T> clazz) {
    return resource().path(MAIN + pathPart).queryParams(params).accept(MediaType.APPLICATION_JSON).get(clazz);
  }
}
